/**
 * RentController
 *
 * @description :: Server-side actions for handling incoming requests.
 * @help        :: See https://sailsjs.com/docs/concepts/actions
 */

module.exports = {

  // action - home
  home: async function (req, res) {
    const numOfItemsPerPage = 8;
    var models = await Rent.find({
      sort: "created",
      limit: numOfItemsPerPage,
    });
    var creatorModels = await Creator.find();
    sails.log("[Session] ", req.session);
    return res.view("rent/home", {
      rents: models,
      creators: creatorModels
    });
  },

  // action - details
  details: async function (req, res) {
    if (!req.session.username) {
      var visitor = "123";
      req.session.username = visitor;
      req.session.abc = visitor;
    }
    sails.log("[Session] ", req.session);
    if (req.method == "GET") {
      var model = await Rent.findOne(req.params.id);
      var creatorModels = await Creator.find();
      if (!model) return res.notFound();
      return res.view("rent/details", {
        rent: model,
        creators: creatorModels,
        message: "full"
      });
    } else {
      if (!req.body.Rent) return res.badRequest("Form-data not received.");
      var models = await Rent.details(req.params.id)
        .set({
          title: req.body.Rent.title,
          url: req.body.Rent.url,
          estate: req.body.Rent.estate,
          bedroom: req.body.Rent.bedroom,
          area: req.body.Rent.area,
          tenant: req.body.Rent.tenant,
          rent: req.body.Rent.rent,
        })
        .fetch();
      if (models.length == 0) return res.notFound();
    }
  },
};
